package com.cardcaptorsakura.controller;

import com.cardcaptorsakura.model.entity.Memory;
import com.cardcaptorsakura.model.entity.UserPreference;
import com.cardcaptorsakura.service.memory.MemoryStorageService;
import com.cardcaptorsakura.service.memory.UserPreferenceService;
import com.cardcaptorsakura.service.memory.VectorSearchService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 记忆管理控制器
 * 提供记忆存储和用户偏好的REST API接口
 */
@Slf4j
@RestController
@RequestMapping("/api/memory")
@RequiredArgsConstructor
@Validated
@Tag(name = "Memory Management", description = "记忆存储和用户偏好管理API")
public class MemoryController {

    private final MemoryStorageService memoryStorageService;
    private final UserPreferenceService userPreferenceService;
    private final VectorSearchService vectorSearchService;

    // ==================== 记忆管理 API ====================

    /**
     * 创建记忆
     */
    @PostMapping("/memories")
    @Operation(summary = "创建记忆", description = "为用户创建新的记忆条目")
    public ResponseEntity<Memory> createMemory(
            @Valid @RequestBody Memory memory) {
        try {
            Memory createdMemory = memoryStorageService.createMemory(memory);
            return ResponseEntity.status(HttpStatus.CREATED).body(createdMemory);
        } catch (Exception e) {
            log.error("Error creating memory", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 获取记忆详情
     */
    @GetMapping("/memories/{memoryId}")
    @Operation(summary = "获取记忆详情", description = "根据ID获取记忆的详细信息")
    public ResponseEntity<Memory> getMemory(
            @Parameter(description = "记忆ID") @PathVariable String memoryId) {
        try {
            Optional<Memory> memory = memoryStorageService.getMemoryById(memoryId);
            return memory.map(ResponseEntity::ok)
                    .orElse(ResponseEntity.notFound().build());
        } catch (Exception e) {
            log.error("Error getting memory: {}", memoryId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 更新记忆
     */
    @PutMapping("/memories/{memoryId}")
    @Operation(summary = "更新记忆", description = "更新指定记忆的信息")
    public ResponseEntity<Memory> updateMemory(
            @Parameter(description = "记忆ID") @PathVariable String memoryId,
            @Valid @RequestBody Memory memory) {
        try {
            memory.setId(memoryId);
            Memory updatedMemory = memoryStorageService.updateMemory(memory);
            return ResponseEntity.ok(updatedMemory);
        } catch (Exception e) {
            log.error("Error updating memory: {}", memoryId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 删除记忆
     */
    @DeleteMapping("/memories/{memoryId}")
    @Operation(summary = "删除记忆", description = "软删除指定的记忆")
    public ResponseEntity<Void> deleteMemory(
            @Parameter(description = "记忆ID") @PathVariable String memoryId) {
        try {
            boolean deleted = memoryStorageService.deleteMemory(memoryId);
            return deleted ? ResponseEntity.noContent().build() 
                          : ResponseEntity.notFound().build();
        } catch (Exception e) {
            log.error("Error deleting memory: {}", memoryId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 获取用户记忆列表
     */
    @GetMapping("/users/{userId}/memories")
    @Operation(summary = "获取用户记忆列表", description = "分页获取用户的记忆列表")
    public ResponseEntity<Page<Memory>> getUserMemories(
            @Parameter(description = "用户ID") @PathVariable String userId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "0") @Min(0) int page,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "20") @Min(1) @Max(100) int size,
            @Parameter(description = "排序字段") @RequestParam(defaultValue = "createdAt") String sortBy,
            @Parameter(description = "排序方向") @RequestParam(defaultValue = "desc") String sortDir) {
        try {
            Sort.Direction direction = "asc".equalsIgnoreCase(sortDir) ? Sort.Direction.ASC : Sort.Direction.DESC;
            Pageable pageable = PageRequest.of(page, size, Sort.by(direction, sortBy));
            
            Page<Memory> memories = memoryStorageService.getUserMemories(userId, pageable);
            return ResponseEntity.ok(memories);
        } catch (Exception e) {
            log.error("Error getting user memories for user: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 搜索相似记忆
     */
    @GetMapping("/users/{userId}/memories/search")
    @Operation(summary = "搜索相似记忆", description = "基于向量相似性搜索用户的记忆")
    public ResponseEntity<List<Memory>> searchSimilarMemories(
            @Parameter(description = "用户ID") @PathVariable String userId,
            @Parameter(description = "搜索查询") @RequestParam @NotBlank String query,
            @Parameter(description = "返回数量限制") @RequestParam(defaultValue = "10") @Min(1) @Max(50) int limit) {
        try {
            List<Memory> memories = vectorSearchService.searchSimilarMemories(userId, query, limit);
            return ResponseEntity.ok(memories);
        } catch (Exception e) {
            log.error("Error searching similar memories for user: {}, query: {}", userId, query, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 获取记忆统计
     */
    @GetMapping("/users/{userId}/memories/statistics")
    @Operation(summary = "获取记忆统计", description = "获取用户的记忆统计信息")
    public ResponseEntity<Map<String, Object>> getMemoryStatistics(
            @Parameter(description = "用户ID") @PathVariable String userId) {
        try {
            Map<String, Object> statistics = memoryStorageService.getMemoryStatistics(userId);
            return ResponseEntity.ok(statistics);
        } catch (Exception e) {
            log.error("Error getting memory statistics for user: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 聚类用户记忆
     */
    @GetMapping("/users/{userId}/memories/clusters")
    @Operation(summary = "聚类用户记忆", description = "对用户记忆进行聚类分析")
    public ResponseEntity<List<VectorSearchService.MemoryCluster>> clusterUserMemories(
            @Parameter(description = "用户ID") @PathVariable String userId,
            @Parameter(description = "最大聚类数") @RequestParam(defaultValue = "5") @Min(2) @Max(20) int maxClusters) {
        try {
            List<VectorSearchService.MemoryCluster> clusters = vectorSearchService.clusterMemories(userId, maxClusters);
            return ResponseEntity.ok(clusters);
        } catch (Exception e) {
            log.error("Error clustering memories for user: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 批量删除记忆
     */
    @DeleteMapping("/users/{userId}/memories")
    @Operation(summary = "批量删除记忆", description = "批量删除用户的记忆")
    public ResponseEntity<Map<String, Object>> batchDeleteMemories(
            @Parameter(description = "用户ID") @PathVariable String userId,
            @RequestBody List<String> memoryIds) {
        try {
            Map<String, Object> result = memoryStorageService.batchDeleteMemories(memoryIds);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("Error batch deleting memories for user: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    // ==================== 用户偏好管理 API ====================

    /**
     * 获取用户偏好
     */
    @GetMapping("/users/{userId}/preferences")
    @Operation(summary = "获取用户偏好", description = "获取用户的个性化偏好设置")
    public ResponseEntity<UserPreference> getUserPreference(
            @Parameter(description = "用户ID") @PathVariable String userId) {
        try {
            Optional<UserPreference> preference = userPreferenceService.getUserPreference(userId);
            return preference.map(ResponseEntity::ok)
                    .orElse(ResponseEntity.notFound().build());
        } catch (Exception e) {
            log.error("Error getting user preference for user: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 保存用户偏好
     */
    @PostMapping("/users/{userId}/preferences")
    @Operation(summary = "保存用户偏好", description = "创建或更新用户的偏好设置")
    public ResponseEntity<UserPreference> saveUserPreference(
            @Parameter(description = "用户ID") @PathVariable String userId,
            @Valid @RequestBody UserPreference preference) {
        try {
            preference.setUserId(userId);
            UserPreference savedPreference = userPreferenceService.saveUserPreference(preference);
            return ResponseEntity.ok(savedPreference);
        } catch (Exception e) {
            log.error("Error saving user preference for user: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 更新语言偏好
     */
    @PutMapping("/users/{userId}/preferences/language")
    @Operation(summary = "更新语言偏好", description = "更新用户的语言偏好设置")
    public ResponseEntity<UserPreference> updateLanguagePreference(
            @Parameter(description = "用户ID") @PathVariable String userId,
            @Valid @RequestBody UserPreference.LanguagePreference languagePreference) {
        try {
            UserPreference updatedPreference = userPreferenceService.updateLanguagePreference(userId, languagePreference);
            return ResponseEntity.ok(updatedPreference);
        } catch (Exception e) {
            log.error("Error updating language preference for user: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 更新人格偏好
     */
    @PutMapping("/users/{userId}/preferences/persona")
    @Operation(summary = "更新人格偏好", description = "更新用户的人格偏好设置")
    public ResponseEntity<UserPreference> updatePersonaPreference(
            @Parameter(description = "用户ID") @PathVariable String userId,
            @Valid @RequestBody UserPreference.PersonaPreference personaPreference) {
        try {
            UserPreference updatedPreference = userPreferenceService.updatePersonaPreference(userId, personaPreference);
            return ResponseEntity.ok(updatedPreference);
        } catch (Exception e) {
            log.error("Error updating persona preference for user: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 更新通知偏好
     */
    @PutMapping("/users/{userId}/preferences/notification")
    @Operation(summary = "更新通知偏好", description = "更新用户的通知偏好设置")
    public ResponseEntity<UserPreference> updateNotificationPreference(
            @Parameter(description = "用户ID") @PathVariable String userId,
            @Valid @RequestBody UserPreference.NotificationPreference notificationPreference) {
        try {
            UserPreference updatedPreference = userPreferenceService.updateNotificationPreference(userId, notificationPreference);
            return ResponseEntity.ok(updatedPreference);
        } catch (Exception e) {
            log.error("Error updating notification preference for user: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 更新隐私偏好
     */
    @PutMapping("/users/{userId}/preferences/privacy")
    @Operation(summary = "更新隐私偏好", description = "更新用户的隐私偏好设置")
    public ResponseEntity<UserPreference> updatePrivacyPreference(
            @Parameter(description = "用户ID") @PathVariable String userId,
            @Valid @RequestBody UserPreference.PrivacyPreference privacyPreference) {
        try {
            UserPreference updatedPreference = userPreferenceService.updatePrivacyPreference(userId, privacyPreference);
            return ResponseEntity.ok(updatedPreference);
        } catch (Exception e) {
            log.error("Error updating privacy preference for user: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 更新界面偏好
     */
    @PutMapping("/users/{userId}/preferences/interface")
    @Operation(summary = "更新界面偏好", description = "更新用户的界面偏好设置")
    public ResponseEntity<UserPreference> updateInterfacePreference(
            @Parameter(description = "用户ID") @PathVariable String userId,
            @Valid @RequestBody UserPreference.InterfacePreference interfacePreference) {
        try {
            UserPreference updatedPreference = userPreferenceService.updateInterfacePreference(userId, interfacePreference);
            return ResponseEntity.ok(updatedPreference);
        } catch (Exception e) {
            log.error("Error updating interface preference for user: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 更新交互偏好
     */
    @PutMapping("/users/{userId}/preferences/interaction")
    @Operation(summary = "更新交互偏好", description = "更新用户的交互偏好设置")
    public ResponseEntity<UserPreference> updateInteractionPreference(
            @Parameter(description = "用户ID") @PathVariable String userId,
            @Valid @RequestBody UserPreference.InteractionPreference interactionPreference) {
        try {
            UserPreference updatedPreference = userPreferenceService.updateInteractionPreference(userId, interactionPreference);
            return ResponseEntity.ok(updatedPreference);
        } catch (Exception e) {
            log.error("Error updating interaction preference for user: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 重置用户偏好
     */
    @PostMapping("/users/{userId}/preferences/reset")
    @Operation(summary = "重置用户偏好", description = "将用户偏好重置为默认值")
    public ResponseEntity<UserPreference> resetUserPreference(
            @Parameter(description = "用户ID") @PathVariable String userId) {
        try {
            UserPreference resetPreference = userPreferenceService.resetUserPreference(userId);
            return ResponseEntity.ok(resetPreference);
        } catch (Exception e) {
            log.error("Error resetting user preference for user: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 导出用户偏好
     */
    @GetMapping("/users/{userId}/preferences/export")
    @Operation(summary = "导出用户偏好", description = "导出用户的偏好设置数据")
    public ResponseEntity<Map<String, Object>> exportUserPreference(
            @Parameter(description = "用户ID") @PathVariable String userId) {
        try {
            Map<String, Object> exportData = userPreferenceService.exportUserPreference(userId);
            return ResponseEntity.ok(exportData);
        } catch (Exception e) {
            log.error("Error exporting user preference for user: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 删除用户偏好
     */
    @DeleteMapping("/users/{userId}/preferences")
    @Operation(summary = "删除用户偏好", description = "删除用户的偏好设置")
    public ResponseEntity<Void> deleteUserPreference(
            @Parameter(description = "用户ID") @PathVariable String userId) {
        try {
            boolean deleted = userPreferenceService.deleteUserPreference(userId);
            return deleted ? ResponseEntity.noContent().build() 
                          : ResponseEntity.notFound().build();
        } catch (Exception e) {
            log.error("Error deleting user preference for user: {}", userId, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    // ==================== 统计和分析 API ====================

    /**
     * 获取用户语言统计
     */
    @GetMapping("/statistics/languages")
    @Operation(summary = "获取用户语言统计", description = "获取按语言分组的用户统计信息")
    public ResponseEntity<Map<String, Long>> getUserLanguageStatistics() {
        try {
            Map<String, Long> statistics = userPreferenceService.getUserLanguageStatistics();
            return ResponseEntity.ok(statistics);
        } catch (Exception e) {
            log.error("Error getting user language statistics", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 获取用户主题统计
     */
    @GetMapping("/statistics/themes")
    @Operation(summary = "获取用户主题统计", description = "获取按主题分组的用户统计信息")
    public ResponseEntity<Map<String, Long>> getUserThemeStatistics() {
        try {
            Map<String, Long> statistics = userPreferenceService.getUserThemeStatistics();
            return ResponseEntity.ok(statistics);
        } catch (Exception e) {
            log.error("Error getting user theme statistics", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}